<template>
  <van-nav-bar title="登录" />
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="result"
        is-link
        readonly
        name="picker"
        label="病区"
        placeholder="点击选择病区"
        :rules="[{ required: true, message: '请选择病区' }]"
        @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
        <van-picker
          :columns="columns"
          :model-value="pickerValue"
          @confirm="onConfirm"
          @cancel="showPicker = false"
        />
      </van-popup>

      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import { dologin } from "@/api/user";
import { queryward } from "@/api/ward";

const router = useRouter();

const username = ref("");
const password = ref("");

const onSubmit = (values) => {
  console.log("submit", values);
  dologin({
    username: username.value,
    password: password.value,
    wardcode: pickerValue.value[0],
  })
    .then((res) => {
      console.log("res", res);
      if (res.code == 0) {
        showNotify({ type: "success", position: "bottom", message: res.msg });
        localStorage.setItem("username", JSON.stringify(res.data));
        localStorage.setItem("ward", JSON.stringify({ wardId: pickerValue.value[0], wardName: result.value }));
        router.push("/");
      } else {
        showNotify({ type: "warning", position: "bottom", message: res.msg });
      }
    })
    .catch((err) => {
      console.log(err);
      showNotify({ type: "warning", position: "bottom", message: err.msg });
    });
};

const showPicker = ref(false);
const columns = ref([]);
const result = ref("");
const pickerValue = ref([]);

queryward({}).then((res) => {
  console.log(res.data);
  columns.value = res.data;
});
const onConfirm = ({ selectedValues, selectedOptions }) => {
  result.value = selectedOptions[0]?.text;
  pickerValue.value = selectedValues;
  showPicker.value = false;
};
</script>

<style></style>
